package com.yjt.class_studio.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yjt.class_studio.common.constant.Constant;
import com.yjt.class_studio.entity.SysUser;
import com.yjt.class_studio.entity.SysUserRole;
import com.yjt.class_studio.pojo.dto.SysUserLoginDTO;
import com.yjt.class_studio.pojo.dto.SysUserSearchDTO;
import com.yjt.class_studio.service.SysRoleService;
import com.yjt.class_studio.service.SysUserRoleService;
import com.yjt.class_studio.service.SysUserService;
import com.yjt.class_studio.utils.DateUtil;
import com.yjt.class_studio.utils.JwtUtils;
import com.yjt.class_studio.utils.R;
import com.yjt.class_studio.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.security.Principal;
import java.util.*;

/**
 * @author Yjt
 * @Date 2023/6/15 13:00
 * @Description
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户（教师、学生）管理")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${avatarImagesFilePath}")
    private String avatarImagesFilePath;

    @PostMapping("/login")
    @ApiOperation(value = "可用于swagger获取token")
    public R login(@RequestBody @Validated SysUserLoginDTO sysUserLoginDTO){
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername,sysUserLoginDTO.getUsername()));
        System.out.println(user);
        if(user == null)
            return R.error("此用户不存在");
        boolean matches = bCryptPasswordEncoder.matches(sysUserLoginDTO.getPassword(), user.getPassword());
        if(!matches)
            return R.error("密码错误");

        String token = JwtUtils.genJwtToken(sysUserLoginDTO.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo",user);
        map.put("token",token);
        map.put("tip","可用于swagger获取token");
        return R.ok(map);

    }

    @PostMapping("/list")
    @ApiOperation(value = "用户列表分页查询")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R getList(@RequestBody SysUserSearchDTO sysUserSearchDTO){
        IPage userList = sysUserService.getAllUserPageData(sysUserSearchDTO);
        Map<String,Object> resultMap=new HashMap<>();
        return R.ok().put("userList",userList);
    }

    /**
     * 验证用户名
     * @param sysUser
     * @return
     */
    @PostMapping("/checkUserName")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R checkUserName(@RequestBody SysUser sysUser){
        if(sysUserService.getByUserName(sysUser.getUsername())==null){
            return R.ok();
        }else{
            return R.error();
        }
    }


    @GetMapping("/info")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R userInfo(Principal principal){
        Map<String,Object> resultMap=new HashMap<>();
        SysUser currentUser = sysUserService.getByUserName(principal.getName());
        resultMap.put("currentUser",currentUser);
        return R.ok(resultMap);
    }

    /**
     * 添加或者修改
     * @param sysUser
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:user:add')"+"||"+"hasAuthority('system:user:edit')")
    public R save(@RequestBody @Valid SysUser sysUser){
        if(sysUser.getId()==null || sysUser.getId()==-1){
            sysUser.setCreateTime(new Date());
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            sysUserService.save(sysUser);
        }else{
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
        }
        return R.ok();
    }

    /**
     * 修改密码
     * @param sysUser
     * @return
     */
    @PostMapping("/updateUserPwd")
    public R updateUserPwd(@RequestBody SysUser sysUser){
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        currentUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getNewPassword()));
        sysUserService.updateById(currentUser);
        return R.ok();
    }

    /**
     * 更新status状态
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/updateStatus/{id}/status/{status}")
    public R updateStatus(@PathVariable(value = "id")Integer id,@PathVariable(value = "status")String status){
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setStatus(status);
        sysUserService.saveOrUpdate(sysUser);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return R.ok();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R findById(@PathVariable(value = "id")Integer id){
        SysUser sysUser = sysUserService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("sysUser",sysUser);
        return R.ok(map);
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @GetMapping("/resetPassword/{id}")
    public R resetPassword(@PathVariable(value = "id")Integer id){
        SysUser sysUser = sysUserService.getById(id);
        sysUser.setPassword(bCryptPasswordEncoder.encode(Constant.DEFAULT_PASSWORD));
        sysUser.setUpdateTime(new Date());
        sysUserService.updateById(sysUser);
        return R.ok();
    }


    /**
     * 修改用户头像
     * @param sysUser
     * @return
     */
    @PostMapping("/updateAvatar")
    @ApiOperation(value ="修改用户头像" )
    public R updateAvatar(@RequestBody SysUser sysUser){
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        currentUser.setAvatar(sysUser.getAvatar());
        sysUserService.updateById(currentUser);
        return R.ok();
    }

    /**
     * 上传用户头像图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadImage")
    @ApiOperation(value ="上传用户头像图片" )
    public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
        Map<String,Object> resultMap=new HashMap<>();
        if(!file.isEmpty()){
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(avatarImagesFilePath+newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","images/userAvatar/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public R delete(@RequestBody Long[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id",ids));
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return R.ok();
    }

    /**
     * 用户角色授权
     * @param userId
     * @param roleIds
     * @return
     */
    @Transactional
    @PostMapping("/grantRole/{userId}")
    @PreAuthorize("hasAuthority('system:user:role')")
    public R grantRole(@PathVariable("userId") Long userId,@RequestBody Long[] roleIds){
        List<SysUserRole> userRoleList=new ArrayList<>();
        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            userRoleList.add(sysUserRole);
        });
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",userId));
        sysUserRoleService.saveBatch(userRoleList);
        redisUtil.removeByPrex(Constant.AUTHORITY_KEY);
        return R.ok();
    }


}
